<template>
  <div class="container">
    <el-card>
      <img class="logo" src="@/assets/image/logo.png" alt="" />
      <!-- 表单 -->
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号" clearable></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input v-model.number="form.code" placeholder="请输入验证码"></el-input>
        </el-form-item>
        <el-form-item prop="agree">
          <el-checkbox v-model="form.agree">我已阅读并同意「用户协议」和「隐私条款」</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('formRef')">登录</el-button>
        </el-form-item>

      </el-form>
    </el-card>
  </div>
</template>

<script>
import auth from '@/utils/token'

export default {
  name: 'LoginPage',
  data () {
    const checkMobile = (rule, value, callback) => {
      if (/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(value)) {
        callback()
      } else {
        callback(new Error('手机号格式错误'))
      }
    }
    return {
      form: {
        mobile: '13355667788',
        code: '246810',
        agree: []
      },
      rules: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { len: 6, message: '验证码为6位数字', trigger: 'blur' }
        ],
        agree: [
          { type: 'array', required: true, message: '请勾选同意协议', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate(async res => {
        if (res) {
          try {
            const res = await this.$http.post('/v1_0/authorizations', this.form)
            // 存储token
            auth.setToken(res.data.data.token)
            this.$message.success('登录成功')
            // 跳转页面
            this.$router.push('/')
          } catch (error) {
            console.error(error)
            this.$message.error(error.response.data.message || '登录失败')
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.container {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background: url('@/assets/image/login.png');

  .el-card {
    width: 440px;
    height: 370px;
    position: absolute;
    left: 50%;
    top: 45%;
    transform: translate(-50%, -50%);
    box-shadow: 0 0 50px rgba(0, 0, 0, 0.1);
    padding-left: 20px;
    padding-right: 20px;
    box-sizing: border-box;

    .logo {
      width: 200px;
      display: block;
      margin: 0 auto 20px;
    }

    .el-button {
      width: 100%;
    }

  }
}
</style>
